﻿using System.Data;
using System.Data.SqlClient;
using System.Globalization;

namespace ContractManagementSystem.DataAccess
{
    public class RoleDataAccess : LogDataAccess
    {
        private const string UserName = "Admin";


        public DataTable FetchAll(string roleName)
        {

            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                //log error
                WriteError(ErrorMessage, UserName);
                return null;
            }

            DataTable result = null;
            try
            {
                //log event                
                WriteEvent("Selecting...", UserName);

                using (var sqlCommand = new SqlCommand("sp_RoleByName_Select", CreateConnection()))
                {
                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.Parameters.AddWithValue("@name", roleName);

                    var adapter = new SqlDataAdapter(sqlCommand);
                    result = new DataTable { Locale = CultureInfo.CurrentCulture };
                    adapter.Fill(result);
                    ErrorMessage = null;
                    //log event
                    WriteEvent("Select success!", UserName);
                }
            }
            catch (SqlException sqlException)
            {
                ErrorMessage = sqlException.Message;

                //log event
                WriteEvent("Select fail!", UserName);

                //log error
                WriteError(ErrorMessage, UserName);

                return result;
            }
            finally
            {
                CloseConnection();
            }

            return result;
        }
    }
}
